package nl.altenpts.net.kad;

import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;

public class RoutingTable implements Serializable {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public RoutingTable(Node root) {	
		this.rootnode = root;
		topbucket = new KBucket(root.getId(), 0);
	}
	
	public List<Node> findNodes(Id target, int n) {
		
		LinkedList<Node> nodes = new LinkedList<Node>();
		DistanceComparator distcomp = new DistanceComparator(target);
		
		topbucket.findNodes(nodes, target, n, distcomp);
		
		return nodes;
	}
	
	public void updateNode(Node node, KBroker kbroker) {
		topbucket.updateNode(node, kbroker);
	}
	
	public void didNodeFind(Id nodeid) {
		topbucket.didNodeFind(nodeid, rootnode.getId().getMatchingPrefix(nodeid));
	}
	
	public void refresh(Kademlia kad) {
		topbucket.refresh(kad);
	}

	public Node getRoot() {
		return rootnode;		
	}
	
	public void writeTable() {
		System.out.println(rootnode.getAddress().getPort());
		topbucket.writeTable();
	}
	
	private KBucket topbucket;
	private Node rootnode;	

}
